<?php


namespace app\admin\service\auth;

use tmcore\base\BaseService;
use app\common\model\auth\Dept;

/**
 * 部门服务类
 */
class DeptService extends BaseService
{
    /**
     * 获取部门列表
     * @return array
     */
    public static function getList(): array
    {
        // 搜索条件
        $searchParam = [
            '=' => ['status'],
            '%like%' => ['name']
        ];
        $where = self::getSearchData($searchParam, []);

        $lists = Dept::where($where)
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->append(['status_desc'])
            ->hidden(['delete_time'])
            ->select()
            ->toArray();
        return linear_to_tree($lists, 'children');
    }

    /**
     * 添加部门
     * @param array $params
     * @return bool
     */
    public static function add(array $params)
    {
        return Dept::add([
            'name' => $params['name'],
            'pid' => $params['pid'],
            'contact' => $params['contact'],
            'mobile' => $params['mobile'],
            'status' => $params['status'],
            'sort' => $params['sort'] ?? 0
        ]);
    }

    /**
     * 编辑部门
     * @param array $params
     * @return bool
     */
    public static function edit(array $params) : bool
    {
        return Dept::edit([
            'name' => $params['name'],
            'pid' => $params['pid'],
            'contact' => $params['contact'],
            'mobile' => $params['mobile'],
            'status' => $params['status'],
            'sort' => $params['sort'] ?? 0
        ], $params['id']);
    }

    /**
     * 删除部门
     * @param array $params
     * @return bool
     */
    public static function delete(array $params)
    {
        return Dept::del($params['id']);
    }

    /**
     * 查看部门详情
     * @param $params
     * @return array
     */
    public static function detail($params) : array
    {
        return Dept::findOrEmpty($params['id'])->toArray();
    }

    /**
     * 部门数据
     * @return array
     */
    public static function getAllData()
    {
        $lists = Dept::where(['status' => 1])
            ->field('id, pid, name')
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->select()
            ->toArray();
        return linear_to_tree($lists, 'children');
    }
}